package com.yuzhi.framework.handler.geometry;


import cn.hutool.core.util.ObjectUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.postgis.PGgeometry;
import org.postgresql.util.PGobject;

public class GeometryTypeHandler extends BaseTypeHandler<Geometry> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType) throws SQLException {
        PGgeometry pgGeometry = new PGgeometry(parameter.toText());
        ps.setObject(i, pgGeometry);
    }

    @Override
    public Geometry getNullableResult(ResultSet rs, String columnName) throws SQLException {
        PGobject pGobject = (PGobject) rs.getObject(columnName);
        if (ObjectUtil.isNull(pGobject)) {
            return null;
        }
        try {
            PGgeometry pgGeometry = new PGgeometry(pGobject.getValue());
            return (pgGeometry != null) ? new WKTReader().read(pgGeometry.getGeometry().getTypeString()+pgGeometry.getGeometry().getValue()) : null;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Geometry getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        PGgeometry pgGeometry = (PGgeometry) rs.getObject(columnIndex);
        try {
            return (pgGeometry != null) ? new WKTReader().read(pgGeometry.getValue()) : null;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Geometry getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        PGgeometry pgGeometry = (PGgeometry) cs.getObject(columnIndex);
        try {
            return (pgGeometry != null) ? new WKTReader().read(pgGeometry.getValue()) : null;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}